#!/usr/bin/env bash
set -e

INPUT_VERSION="$1"

# 获取最终版本号
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
GO_VERSION=$(bash "$SCRIPT_DIR/resolve-version.sh" "$INPUT_VERSION")
echo "🎯 解析出的 Go 版本为: $GO_VERSION"

# 系统识别
OS=$(uname | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

if [[ "$ARCH" == "x86_64" || "$ARCH" == "amd64" ]]; then
  ARCH="amd64"
elif [[ "$ARCH" == "aarch64" || "$ARCH" == "arm64" ]]; then
  ARCH="arm64"
else
  echo "❌ 不支持的架构: $ARCH"
  exit 1
fi

if [[ "$OS" == "mingw"* || "$OS" == "msys"* || "$OS" == "cygwin"* ]]; then
  OS="windows"
  EXT="zip"
elif [[ "$OS" == "darwin" ]]; then
  OS="darwin"
  EXT="tar.gz"
elif [[ "$OS" == "linux" ]]; then
  OS="linux"
  EXT="tar.gz"
else
  echo "❌ 不支持的系统: $OS"
  exit 1
fi

FILE="go${GO_VERSION}.${OS}-${ARCH}.${EXT}"
URL="https://golang.google.cn/dl/${FILE}"
INSTALL_DIR="$HOME/go"

echo "⬇️ 下载 Go $GO_VERSION: $URL"
curl -fsSL "$URL" -o "$FILE"

mkdir -p "$INSTALL_DIR"
if [[ "$EXT" == "zip" ]]; then
  unzip -q "$FILE" -d "$INSTALL_DIR"
  mv "$INSTALL_DIR/go"/* "$INSTALL_DIR"
else
  tar -C "$INSTALL_DIR" -xzf "$FILE" --strip-components=1
fi

# 设置环境变量
echo "$INSTALL_DIR/bin" >> "$GITHUB_PATH"
echo "GOROOT=$INSTALL_DIR" >> "$GITHUB_ENV"
echo "GOPATH=$HOME/go-packages" >> "$GITHUB_ENV"
mkdir -p "$HOME/go-packages"

echo "✅ Go $GO_VERSION 安装完成。"
